package com.t.blog.controller;
import cn.hutool.jwt.JWTUtil;
import com.t.blog.dto.SysUserDto;
import com.t.blog.service.SysUserService;
import com.t.blog.utils.PassUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.*;
import org.t.pro.pojo.SysLoginUserPojo;
import org.t.pro.pojo.SysRegisterUserPojo;
import org.t.pro.vo.SysUser;
import t.microservices.fw.common.interResult.R;
import t.microservices.fw.common.result.ResultEnum;
import javax.validation.Valid;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 〈一句话功能简述〉<br>
 * 〈权限校验控制器〉
 *
 * @author a0000
 * @create 2024/2/3 22:54
 * @since 1.0.0
 */
@RestController
@CrossOrigin
@RequestMapping("auth")
public class AuthController {


    @Autowired
    private SysUserService userService;

    @Autowired
    private AuthenticationManager authenticationManager;


    @Autowired
    private PassUtils passUtils;

    @PostMapping("login")
    public R UserLogin(@Valid @RequestBody SysLoginUserPojo LoginUser){
        SysUserDto user = userService.getUserSalt(LoginUser.getUserName());
        if (user == null){
            throw new BadCredentialsException("用户账号不存在");
        }
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(user,sysUser);
        sysUser.setPassword(LoginUser.getPassword());
        sysUser = passUtils.PassWithSalt(sysUser);
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(),sysUser.getPassword());
        try{
            Authentication authenticate = authenticationManager.authenticate(token);
            if (!authenticate.isAuthenticated()){
                return R.fail(ResultEnum.FAIL_USER_UNEXIST);
            }
            //校验通过，创建Token
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("username",user.getUsername());
            map.put("nickname",user.getNickName());
            //获取用户权限
            String authority = "";
            Collection<? extends GrantedAuthority> authorities = authenticate.getAuthorities();
            for (GrantedAuthority grantedAuthority : authorities) {
                authority  += ","+grantedAuthority.getAuthority();
            }
            map.put("roles",authority);
            //设置token过期时间
            map.put("expire_time", System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 15);
            String userToken = JWTUtil.createToken(map, user.getSalt().getBytes());
            HashMap<String,String> result = new HashMap<>();
            result.put("accessToken",userToken);
            return R.success(result);
        }catch (Exception e){
            System.out.println(e);
        }
        return R.fail(ResultEnum.FAIL_USER_PASSERROR.getMessage());
    }

    @PostMapping("register")
    public R UserRegister(@Valid @RequestBody SysRegisterUserPojo sysUserDto){
        boolean result = userService.saveUser(sysUserDto);
        if (result)  return R.success("成功添加一名用户");
        else  return R.fail(ResultEnum.FAIL);
    }
}
